package com.cyh.structurealgorithm;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;

public class GreedyAlgorithm {
    public static void test() {
        HashMap<String, HashSet<String>> broadcasts = new HashMap<>();

        HashSet<String> hashSet1 = new HashSet<>();
        hashSet1.add("北京");
        hashSet1.add("上海");
        hashSet1.add("天津");

        HashSet<String> hashSet2 = new HashSet<>();
        hashSet2.add("广州");
        hashSet2.add("北京");
        hashSet2.add("深圳");

        HashSet<String> hashSet3 = new HashSet<>();
        hashSet3.add("成都");
        hashSet3.add("上海");
        hashSet3.add("杭州");

        HashSet<String> hashSet4 = new HashSet<>();
        hashSet4.add("上海");
        hashSet4.add("天津");

        HashSet<String> hashSet5 = new HashSet<>();
        hashSet5.add("杭州");
        hashSet5.add("大连");

        broadcasts.put("K1", hashSet1);
        broadcasts.put("K2", hashSet2);
        broadcasts.put("K3", hashSet3);
        broadcasts.put("K4", hashSet4);
        broadcasts.put("K5", hashSet5);

        //所有地区，他会不断减少
        HashSet<String> allArreas = new HashSet<>();
        allArreas.add("北京");
        allArreas.add("上海");
        allArreas.add("天津");
        allArreas.add("广州");
        allArreas.add("深圳");
        allArreas.add("成都");
        allArreas.add("杭州");
        allArreas.add("大连");

        //存放选择的电台结合
        ArrayList<String> selects = new ArrayList<>();

        //不同地区跟所有地区的交集
        HashSet<String> tempSet = new HashSet<>();

        //最多未覆盖的电台
        String maxkey = null;

        while(allArreas.size() != 0) {
            maxkey = null;

            for(String key : broadcasts.keySet()) {
                tempSet.clear();
                HashSet<String> areas = broadcasts.get(key);
                tempSet.addAll(areas);
                tempSet.retainAll(allArreas); //两个集合的交集
                if(tempSet.size() > 0 && (maxkey == null || tempSet.size() > broadcasts.get(maxkey).size())) {
                    maxkey = key;
                }
            }
            if(maxkey != null) {
                selects.add(maxkey);
                allArreas.removeAll(broadcasts.get(maxkey));
            }
        }

        System.out.println("贪婪算法：" + selects);
    }
}
